﻿using LogisticsTrackingWebApi.Models;
using LogisticsTrackingWebApi.Services;
using Microsoft.AspNetCore.Mvc;

namespace LogisticsTrackingWebApi.Controllers
{

    /// <summary>
    /// 物流查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class LogisticsController : ControllerBase
    {
        private readonly ILogisticsService _logisticsService;
        private readonly ILogger<LogisticsController> _logger;

        public LogisticsController(ILogisticsService logisticsService, ILogger<LogisticsController> logger)
        {
            _logisticsService = logisticsService;
            _logger = logger;
        }

        /// <summary>
        /// 获取支持的物流公司列表
        /// </summary>
        /// <returns>物流公司列表</returns>
        [HttpGet("companies")]
        public async Task<ActionResult<List<LogisticsCompany>>> GetSupportedCompanies()
        {
            try
            {
                var companies = await _logisticsService.GetSupportedCompaniesAsync();
                return Ok(companies);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物流公司列表失败");
                return StatusCode(500, "获取物流公司列表失败");
            }
        }

        /// <summary>
        /// 根据订单号查询物流信息
        /// </summary>
        /// <param name="orderNumber">订单号</param>
        /// <param name="companyCode">物流公司代码（可选）</param>
        /// <returns>物流订单信息</returns>
        [HttpGet("orders/{orderNumber}")]
        public async Task<ActionResult<LogisticsOrder>> GetOrderInfo(string orderNumber, [FromQuery] string? companyCode = null)
        {
            if (string.IsNullOrWhiteSpace(orderNumber))
            {
                return BadRequest("订单号不能为空");
            }

            try
            {
                var orderInfo = await _logisticsService.GetOrderInfoAsync(orderNumber, companyCode);
                return Ok(orderInfo);
            }
            catch (KeyNotFoundException ex)
            {
                _logger.LogWarning(ex, "查询订单信息失败：{Message}", ex.Message);
                return NotFound(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询订单信息时发生错误");
                return StatusCode(500, "查询订单信息时发生错误");
            }
        }
    }
}